package io.gitee.jingtuo.android.device

import android.os.Build
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader

object SysProManager {

    private const val TAG = "SysPro"

    private const val COMMAND = "getprop"

    private var properties: Map<String, String>? = null

    suspend fun initProperties(): Boolean {
        return withContext(Dispatchers.IO) {
            val process = ProcessBuilder(COMMAND)
                .start()
            val reader: BufferedReader
            var lines: List<String>? = null
            //vivo S10 Pro手机上验证, 先读取errorStream会卡住
            try {
                reader = BufferedReader(InputStreamReader(process.inputStream))
                lines = reader.readLines()
                reader.close()
                val map = mutableMapOf<String, String>()
                for (item: String in lines) {
                    val keyValue = item.split(":")
                    if (keyValue.size >= 2) {
                        var key = keyValue[0]
                        var value = keyValue[1]
                        if (key.startsWith("[") && key.endsWith("]")) {
                            key = key.substring(1, key.length - 1)
                        }
                        if (value.startsWith("[") && value.endsWith("]")) {
                            value = value.substring(1, value.length - 1)
                        }
                        if (value.startsWith(" [") && value.endsWith("]")) {
                            value = value.substring(2, value.length - 1)
                        }
                        map.put(key, value)
                    }
                }
                properties = map.toMap()
                return@withContext true
            } catch (e: Exception) {
                Log.e(TAG, "getprop error", e)
            }
            return@withContext false
        }
    }

    /**
     * 获取属性的值
     */
    fun getProperty(key: String): String {
        return properties?.get(key) ?: ""
    }

    fun getDeviceName(): Pair<String, String>? {
        val deviceNameKey = when (Build.BRAND) {
            "HUAWEI", "HONOR" -> "ro.config.marketing_name"
            "Xiaomi", "Redmi" -> "ro.product.marketname"
            "vivo" -> "ro.vivo.market.name"
            else -> {
                val result = properties?.keys?.filter {
                    it.contains("market", true) && it.contains("name", true)
                }
                if (result.isNullOrEmpty()) {
                    ""
                } else {
                    result[0]
                }
            }
        }

        if (deviceNameKey.isEmpty()) {
            return null
        }
        val deviceNameValue = getProperty(deviceNameKey)
        return Pair(deviceNameKey, deviceNameValue)
    }

    fun getProperties(): List<Pair<String, String>> {
        val list = mutableListOf<Pair<String, String>>()
        properties?.let {
            it.forEach { item ->
                list.add(Pair(item.key, item.value))
            }
        }
        return list.toList()
    }

    fun getBrandOSName(): Pair<String, String> {
        val key = "custom.system.name"
        return when (Build.BRAND) {
            "HUAWEI" -> Pair(key, "HarmonyOS")
            "HONOR" -> Pair(key, "MagicOS")
            "Xiaomi", "Redmi" -> Pair(key, "MIUI")
            "vivo" -> Pair(key, "OriginOS")
            "OPPO" -> Pair(key, "ColorOS")
            else -> Pair(key, "Android")
        }
    }

    fun getBrandOSVersion(): Pair<String, String> {
        if ("HONOR".equals(Build.BRAND, true)) {
            //荣耀品牌
            return Pair("mscw.hnouc.patch.version", getProperty("mscw.hnouc.patch.version"))
        }
        if ("Xiaomi".equals(Build.BRAND, true)
            || "Redmi".equals(Build.BRAND, true)) {
            //小米,红米
            return Pair("persist.sys.grant_version", getProperty("persist.sys.grant_version"))
        }
        if ("vivo".equals(Build.BRAND, true)) {
            //vivo
            return Pair("ro.vivo.product.version", getProperty("ro.vivo.product.version"))
        }
        //华为品牌, 或者其他品牌
        val modelAndVersion = Build.DISPLAY
        val version = modelAndVersion.replace(Build.MODEL, "").trim()
        return Pair("custom.system.version", version)
    }
}